package com.mybonita.cas;

import org.bonitasoft.console.common.server.auth.AuthenticationManager;
import org.bonitasoft.engine.authentication.AuthenticationConstants;
import org.bonitasoft.engine.authentication.GenericAuthenticationService;
import org.bonitasoft.engine.authentication.impl.AuthenticationServiceImpl;
import org.bonitasoft.engine.commons.LogUtil;
import org.bonitasoft.engine.identity.IdentityService;
import org.bonitasoft.engine.log.technical.TechnicalLogSeverity;
import org.bonitasoft.engine.log.technical.TechnicalLoggerService;
import org.jasig.cas.client.validation.Cas30ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidationException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CASAuthenticationService implements GenericAuthenticationService {
    //private static final Logger LOGGER = Logger.getLogger(CASAuthenticationService.class.getName());
    @Autowired
    private AuthenticationServiceImpl authenticationService;
    private final IdentityService identityService;

    private final TechnicalLoggerService logger;

    public CASAuthenticationService(final IdentityService identityService, final TechnicalLoggerService logger) {
        this.identityService = identityService;
        this.logger = logger;
    }
    public String checkUserCredentials(Map<String, Serializable> credentials) {
        final String methodName = "checkUserCredentials";
        logger.log(this.getClass(), TechnicalLogSeverity.TRACE, LogUtil.getLogAfterMethod(this.getClass(), methodName));
        // local login:
        if (credentials.get(AuthenticationConstants.CAS_TICKET) == null) {
            return authenticationService.checkUserCredentials(credentials);
        }

        // cas login:
        Cas30ServiceTicketValidator validator =
                new Cas30ServiceTicketValidator("https://testcas.sasu.edu.cn:8443/cas");

        try {
            String username=validator.validate((String) credentials.get(AuthenticationConstants.CAS_TICKET),
                    "https://testbpm.sasu.edu.cn:8080/bonita/loginservice")
                    .getPrincipal().getName();

            return username;

        } catch (TicketValidationException e) {
            e.printStackTrace();
        }

        return null;
    }
}
